import storage from 'store'
import { login, getInfo, logout, GetConfig } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    is_login:false,
    is_loading:false,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_LOGIN:(state,is_login)=>{
      state.is_login = is_login
    },
    SET_LOADING:(state,is_loading)=>{
      state.is_loading = is_loading
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          console.log('-------------response------------', response)
          const result = response
          localStorage.setItem('merchant_id',result.data.merchant_id)
          const type = result.data.type
          localStorage.setItem('type',type)
          let user_type_price = ''
          if(type==1){
            // 分销
            user_type_price = 'distribution_price'
          }else if(type==2){
            // 渠道
            user_type_price = 'channel_price'
          }else if(type==3){
            // 批发
            user_type_price = 'trade_price'
          }
          localStorage.setItem('user_type_price',user_type_price)
          commit('SET_TOKEN', result.data.token)
          commit('SET_LOGIN', true)
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    },
    Changeloading ({ commit }, loading) {
      return new Promise((resolve, reject) => {
          commit('SET_LOADING',true);
          commit('SET_LOGIN', true)
        resolve()
      })
    },
    GetConfig ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        GetConfig(userInfo).then(response => {
          const result = response
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    },
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        storage.remove(ACCESS_TOKEN)
        resolve()
      })
    }

  }
}

export default user
